var App = App || {};
App.isJson = function (obj) {
    return typeof (obj) === "object" && Object.prototype.toString.call(obj).toLowerCase() === "[object object]" && !obj.length;
};

App.message = function (msg, type, time) {
    let t = time || 3000;
    let $alert = $('<div />', {
        'class': 'alert alert-warning',
        'html': [
            '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>',
            msg
        ]
    });
    let obj = $('.right, .login-error');
    obj.find('.alert').remove();
    obj.before($alert);
    window.setTimeout(function () {
        $('.alert').fadeOut(t, function () {
            $(this).remove();
        });
    }, t);
};

App.tip = function ($this, message, time) {
    time = time || 4000;
    $this.tooltip({'title': message, 'trigger': 'manual'});
    $this.tooltip('show');
    window.setTimeout(function () {
        $this.tooltip('destroy');
    }, time);
};

App.modalTemplate = function (title, content) {
    return '<div class="modal fade" tabindex="-1" role="dialog">\n' +
        '  <div class="modal-dialog" role="document">\n' +
        '    <div class="modal-content">\n' +
        '      <div class="modal-header">\n' +
        '        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>\n' +
        '        <h4 class="modal-title">' + title + '</h4>\n' +
        '      </div>\n' +
        '      <div class="modal-body">\n' + content + '\n' + '</div>\n' +
        '    </div>\n' +
        '  </div>\n' +
        '</div>'
};

App.dialog = function ($this) {
    let $body = $('body');
    let $title = $this.attr('title') || $this.data('original-title');
    $.ajax({
        type: 'GET',
        url: $this.attr('href'),
        success: function (html) {
            let $modal = $('.modal');
            if ($modal.length) {
                if ($title === undefined) {
                    $title = $('.modal-title').html();
                }
                $modal.remove();
                $('.modal-backdrop').remove();
            }
            let _html = App.modalTemplate($title, html);
            $body.append(_html);
            let $_modal = $body.find('.modal');
            console.log($_modal);
            $_modal.modal();
            $_modal.on('hidden.bs.modal', function (e) {
                $_modal.remove();
            });
        },
        error: function (xhr) {
            if (xhr.status !== 200) {
                console.log(xhr.responseText);
                App.message(xhr.responseText, 'error', 5000);
            }
        }
    });

};

App.ajax = {};
App.ajax.request = function ($this, method, option) {
    let options = $.extend({type: 'json'}, option);
    let text = $this.attr('title') || $this.data('original-title') || $this.val() || $this.text();

    $.ajax({
        type: method,
        url: options.url || $this.attr('href'),
        data: options.data,
        dataType: options.type || 'json',
        context: $this,
        beforeSend: options.beforeSend || function () {
            $this.attr('disabled', 'disabled').addClass('disabled');
        },
        error: options.error || function (jqXHR, statusText, error) {
            let title = typeof error === 'object' ? statusText : error;
            $this.removeAttr('disabled', 'disabled').removeClass('disabled');
            App.tip($this, jqXHR.responseText, 5000);
        },
        success: options.success || function (result) {
            if (!App.isJson(result) || result['code'] > 0) {
                $this.removeAttr('disabled', 'disabled').removeClass('disabled');
                App.tip($this, result['msg']);
                return;
            }
            if (result.code === 0) {
                window.setTimeout(function () {
                    $this.removeAttr('disabled', 'disabled').removeClass('disabled');
                    let redirect = $this.attr('redirect') || result['redirect'] || false;
                    // App.tip($this, result['msg']);

                    if (redirect) {
                        window.location.href = redirect;
                    } else {
                        window.location.reload();
                    }
                }, 2000);
            }
        }
    });
};

App.ajax.get = function ($this, options) {
    App.ajax.request($this, 'GET', options);
};

App.ajax.post = function ($this, option) {
    let options = option || {};
    if (!options.data && !options.url) {
        let form = $this.parents('form');
        let url = form.attr('action');
        let data = form.serialize();
        options = $.extend({'data': data, 'url': url}, options);
    }
    App.ajax.request($this, 'POST', options);
};

(function ($) {
    $.fn.ajaxGet = function (options) {
        return this.each(function () {
            App.ajax.get($(this), options);
        });
    };
})(jQuery);

(function ($) {
    $.fn.ajaxPost = function (options) {
        return this.each(function () {
            App.ajax.post($(this), options);
        });
    };
})(jQuery);

(function ($) {

    $('[data-toggle="tooltip"]').tooltip();

    $('.hint-block').each(function () {
        let $hint = $(this);
        $hint.parent().find('input, textarea').attr('placeholder', $hint.html());
    });

    $('#user-start, #user-stop').click(function () {
        WdatePicker({skin: 'default', dateFmt: 'H:mm:ss'});
    });

})(jQuery);

$(function () {
    $(document).on('afterValidateAttribute', 'form', function (event, attribute, message) {
        let $form = $(this);
        let $error = $form.find(attribute.container).find(attribute.error);
        let px = message.length > 0 ? '-10px' : 0;
        $error.css('margin-bottom', px);
        return false;
    });

    $(document).on('beforeSubmit', 'form', function () {
        let form = $(this);
        console.log('beforeSubmit');
        if (form.find('.has-error').length) {
            return false;
        }
        form.find(':submit').ajaxPost();
        return false;
    });

    $(document).on(':submit', 'form', function () {
        let form = $(this);
        form.find(':submit').ajaxPost();
        return false;
    });

    $(document).on('click', 'body :submit', function () {
        let form = $(this);
        form.ajaxPost();
        return false;
    });

    $(document).on('click', 'body .modal-body a', function () {
        App.dialog($(this));
        return false;
    });

    $(document).on('click', '.dialog', function () {
        let $this = $(this);
        App.dialog($this);
        return false;
    });
});

$(function () {
    $('.empty').parent('td').css('border-bottom', 'none');

    $('.btn-search').on('click', function () {
        $(this).parents('form').submit();
        return false;
    });

    $(document).on('click', '.select-on-check-all', function () {
        let $checked = $(this).prop('checked');
        $('[name="selection[]"]').prop("checked", $checked);
        let $toolBar = $('.btn-toolbar .btn');
        if ($checked) {
            $toolBar.removeClass('disabled');
        } else {
            $toolBar.addClass('disabled');
        }
    });

    $(document).on('click', '[name="selection[]"]', function () {
        let n = $("[name=\"selection[]\"]:checked").length;
        let $toolBar = $('.btn-toolbar .btn');
        if (n > 0) {
            console.log(n);
            $toolBar.removeClass('disabled');
        } else {
            $toolBar.addClass('disabled');
        }
    });

    $(document).on('click', '.btn-toolbar .btn', function () {
        let $this = $(this);

        let id_list = [];
        $("[name=\"selection[]\"]:checked").each(function () {
            id_list.push($(this).val());
        });
        if (id_list.length <= 0) {
            App.tip($this, '请选择要操作的数据');
            return false;
        }
        window.location.href = $this.attr('href') + id_list.join(',');
    });

    $(document).on('click', '.fwd :checkbox', function () {
        let $this = $(this);
        let checked = $this.prop('checked');
        $('.fwd').find(':checkbox').each(function () {
            $(this).prop('checked', !checked);
        });
        $this.prop('checked', checked);
    });

    let $alert = $('.alert');
    if ($alert.length) {
        window.setTimeout(function () {
            $alert.fadeOut(500, function () {
                $alert.remove();
            });
        }, 5000);
    }
    if ($('#HardDiskFree').length) {
        function show() {
            $.getJSON(window['hardware'], function (res) {
                let data = res['data'];
                if(data['CPUTemperature']){
                    for (let i in data){
                        $('#' + i).text(data[i]);
                    }
                }
            });
        }
        show();
        window.setInterval(function () {
            show();
        }, 2000)
    }
});